
// ---------------------------------------------------
// | File Name   : delay.c
// | Author   	 : chagn7z
// | Create Date : 2014-4-8
// ---------------------------------------------------

#include "stm32f10x.h"
#include "delay.h"
#include "lcd1602.h"
#include "user_cfg.h"

u16 lcd_light_sec = 0;

void delay_init()
{

	SysTick_CLKSourceConfig(SysTick_CLKSource_HCLK_Div8);
	
	SysTick->CTRL &= ~((u32)1 << 2);
	
	SysTick->LOAD = (u32)9;
	SysTick->VAL  = (u32)0;
	
	SysTick->CTRL |= ((u32)1 << 1);
	SysTick->CTRL |= ((u32)1);
}

void delay_us(u32 nus)
{
	u32 temp;
	
	SysTick->CTRL &= ~((u32)1);
	SysTick->VAL   = (u32)0;
	SysTick->LOAD  = (u32)(9 * nus);
	
	SysTick->CTRL |= (u32)1;
	
	do
	{
		temp = SysTick->CTRL;
	}while((temp & (u32)1) && !(temp & (u32)(1 << 16)));
	
	SysTick->CTRL &= ~(u32)1;
	SysTick->VAL   = (u32)0;
}

void timer_init(void)
{
	TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
	NVIC_InitTypeDef NVIC_InitStructure;

	RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2,ENABLE);

	TIM_DeInit(TIM2); 	 
	TIM_InternalClockConfig(TIM2);	 

	TIM_TimeBaseStructure.TIM_Period=2000;		
	TIM_TimeBaseStructure.TIM_Prescaler=(36000-1);	  
	TIM_TimeBaseStructure.TIM_ClockDivision=TIM_CKD_DIV1;
	TIM_TimeBaseStructure.TIM_CounterMode=TIM_CounterMode_Up;	 
	TIM_TimeBaseInit(TIM2,&TIM_TimeBaseStructure);

	TIM_ClearFlag(TIM2,TIM_FLAG_Update);				 
	TIM_ITConfig(TIM2,TIM_IT_Update,ENABLE);	

	NVIC_PriorityGroupConfig(NVIC_PriorityGroup_0);   
	NVIC_InitStructure.NVIC_IRQChannel = TIM2_IRQn;	  
	NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;    
	NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1;          
	NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
	NVIC_Init(&NVIC_InitStructure);

	TIM_Cmd(TIM2,ENABLE);	
}

void TIM2_IRQHandler(void)
{

	if(TIM_GetITStatus(TIM2, TIM_IT_Update) != RESET)
	{	
		TIM_ClearITPendingBit(TIM2 , TIM_FLAG_Update);
		
		if (lcd_light_sec < 11)
			LCD_LIGHT = 1;
		else
			LCD_LIGHT = 0;

		lcd_light_sec ++;

		if (lcd_light_sec >= 11)
			lcd_light_sec = 11;
	}
}

